{% extends "base.html" %}

{% block title %}测试结果 - UI自动化测试平台{% endblock %}

{% block content %}
<div class="row">
    <div class="col-md-12">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <div class="d-flex align-items-center">
                <h2 class="mb-0 me-4"><span id="currentDateTime"></span></h2>
                <div class="d-flex align-items-center">
                    <input type="date" id="dateFilter" class="form-control me-2" placeholder="选择日期">
                    <button class="btn btn-outline-secondary" id="clearDateFilter" title="清除日期筛选">
                        <i class="bi bi-x"></i>
                    </button>
                </div>
            </div>
            <button class="btn btn-primary" id="refreshResultsBtn">
                <i class="bi bi-arrow-clockwise"></i> 刷新
            </button>
        </div>
        
        <div class="row">
            <!-- 左侧二级菜单 -->
            <div class="col-md-3">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <button class="btn btn-link" type="button" data-bs-toggle="collapse" data-bs-target="#submenuCollapse">
                                测试结果导航
                            </button>
                        </h5>
                    </div>
                    <div id="submenuCollapse" class="collapse show">
                        <div class="list-group list-group-flush">
                            <button class="list-group-item list-group-item-action active" id="chartTab" data-tab="chart">
                                <i class="bi bi-graph-up"></i> 图表统计
                            </button>
                            <button class="list-group-item list-group-item-action" id="logTab" data-tab="log">
                                <i class="bi bi-list"></i> 测试日志
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 右侧内容区域 -->
            <div class="col-md-9">
                <!-- 图表统计页面 -->
                <div id="chartContent" class="tab-content active">
                    <div class="card">
                        <div class="card-header">
                            <h5>测试结果统计</h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <h6>按优先级统计</h6>
                                    <canvas id="priorityChart" width="400" height="200"></canvas>
                                </div>
                                <div class="col-md-6">
                                    <h6>按结果统计</h6>
                                    <canvas id="resultChart" width="400" height="200"></canvas>
                                </div>
                            </div>
                            <div class="row mt-4">
                                <div class="col-md-12">
                                    <h6>执行趋势</h6>
                                    <canvas id="trendChart" width="800" height="300"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 测试日志页面 -->
                <div id="logContent" class="tab-content" style="display: none;">
                    <div class="card">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-striped table-hover" id="testResultsTable">
                                    <thead>
                                        <tr>
                                            <th>序号</th>
                                            <th>测试用例</th>
                                            <th>状态</th>
                                            <th>执行时间(秒)</th>
                                            <th>执行时间</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <!-- 数据将通过JavaScript动态加载 -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script src="{{ url_for('static', filename='js/chart.min.js') }}"></script>
<script>
    // 当前激活的标签页
    var activeTab = 'chart';
    // 日期筛选值
    var dateFilter = '';
    
    // 更新当前时间显示
    function updateDateTime() {
        var now = new Date();
        var year = now.getFullYear();
        var month = String(now.getMonth() + 1).padStart(2, '0');
        var day = String(now.getDate()).padStart(2, '0');
        var hours = String(now.getHours()).padStart(2, '0');
        var minutes = String(now.getMinutes()).padStart(2, '0');
        var seconds = String(now.getSeconds()).padStart(2, '0');
        
        var dateTimeString = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
        document.getElementById('currentDateTime').textContent = dateTimeString;
    }
    
    // 页面加载时更新时间
    updateDateTime();
    
    // 每秒更新一次时间
    setInterval(updateDateTime, 1000);
    
    // 加载测试结果列表
    function loadTestResults() {
        // 构建API URL，包含日期筛选参数
        var apiUrl = '/api/testresults';
        if (dateFilter) {
            apiUrl += '?date=' + encodeURIComponent(dateFilter);
        }
        
        $.get(apiUrl)
            .done(function(data) {
                if (activeTab === 'log') {
                    displayTestResults(data);
                }
                if (activeTab === 'chart') {
                    updateCharts(data);
                }
            })
            .fail(function() {
                alert('加载测试结果失败');
            });
    }
    
    // 显示测试结果列表
    function displayTestResults(data) {
        var tbody = $('#testResultsTable tbody');
        tbody.empty();
        
        data.forEach(function(result, index) {
            var statusClass = result.status === 'PASS' ? 'success' : result.status === 'FAIL' ? 'danger' : 'warning';
            var statusText = result.status === 'PASS' ? '通过' : result.status === 'FAIL' ? '失败' : '错误';
            var row = `
                <tr>
                    <td>${index + 1}</td>
                    <td>${result.test_case ? result.test_case.name : '未知用例'}</td>
                    <td><span class="badge bg-${statusClass}">${statusText}</span></td>
                    <td>${result.execution_time ? result.execution_time.toFixed(2) : ''}</td>
                    <td>${formatDate(result.executed_at)}</td>
                    <td>
                        <button class="btn btn-sm btn-primary" onclick="viewResultDetail(${result.id})">
                            <i class="bi bi-eye"></i>
                        </button>
                    </td>
                </tr>
            `;
            tbody.append(row);
        });
    }
    
    // 更新图表
    function updateCharts(data) {
        // 按优先级统计
        var priorityStats = {};
        // 按结果统计
        var resultStats = {};
        // 按时间统计（用于趋势图）
        var trendStats = {};
        
        data.forEach(function(result) {
            // 统计优先级
            if (result.test_case && result.test_case.priority) {
                var priority = result.test_case.priority;
                priorityStats[priority] = (priorityStats[priority] || 0) + 1;
            }
            
            // 统计结果
            var status = result.status;
            resultStats[status] = (resultStats[status] || 0) + 1;
            
            // 统计执行趋势（按日期）
            if (result.executed_at) {
                // 提取日期部分（YYYY-MM-DD）
                var date = result.executed_at.split('T')[0];
                if (!trendStats[date]) {
                    trendStats[date] = {PASS: 0, FAIL: 0, ERROR: 0, BLOCKED: 0};
                }
                
                // 分类统计
                if (status === 'PASS') {
                    trendStats[date].PASS++;
                } else if (status === 'FAIL') {
                    trendStats[date].FAIL++;
                } else if (status === 'ERROR') {
                    trendStats[date].ERROR++;
                } else if (status.startsWith('Blocked by Case')) {
                    trendStats[date].BLOCKED++;
                }
            }
        });
        
        // 更新优先级图表
        updatePriorityChart(priorityStats);
        
        // 更新结果图表
        updateResultChart(resultStats);
        
        // 更新趋势图表
        updateTrendChart(trendStats);
    }
    
    // 更新优先级图表
    function updatePriorityChart(stats) {
        var ctx = document.getElementById('priorityChart').getContext('2d');
        
        // 如果图表已存在，先销毁
        if (window.priorityChart && typeof window.priorityChart.destroy === 'function') {
            window.priorityChart.destroy();
        }
        
        // 准备数据
        var labels = [];
        var data = [];
        var backgroundColors = [];
        
        // 定义优先级顺序和颜色
        var priorityOrder = ['P1', 'P2', 'P3', 'P4'];
        var priorityColors = {
            'P1': '#dc3545', // 红色
            'P2': '#fd7e14', // 橙色
            'P3': '#ffc107', // 黄色
            'P4': '#28a745'  // 绿色
        };
        
        priorityOrder.forEach(function(priority) {
            if (stats[priority]) {
                labels.push(priority);
                data.push(stats[priority]);
                backgroundColors.push(priorityColors[priority]);
            }
        });
        
        // 创建图表
        window.priorityChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [{
                    label: '测试用例数量',
                    data: data,
                    backgroundColor: backgroundColors,
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1
                        }
                    }
                }
            }
        });
    }
    
    // 更新结果图表
    function updateResultChart(stats) {
        var ctx = document.getElementById('resultChart').getContext('2d');
        
        // 如果图表已存在，先销毁
        if (window.resultChart && typeof window.resultChart.destroy === 'function') {
            window.resultChart.destroy();
        }
        
        // 准备数据
        var labels = [];
        var data = [];
        var backgroundColors = [];
        
        // 定义结果类型和颜色
        var resultTypes = {
            'PASS': { label: '通过', color: '#28a745' },
            'FAIL': { label: '失败', color: '#dc3545' },
            'ERROR': { label: '错误', color: '#ffc107' },
            'Blocked by Case': { label: '阻塞(错误)', color: '#6c757d' }
        };
        
        Object.keys(stats).forEach(function(status) {
            // 处理Blocked by Case状态，统一归类到Blocked by Case
            var displayStatus = status;
            if (status.startsWith('Blocked by Case')) {
                displayStatus = 'Blocked by Case';
            }
            
            var displayInfo = resultTypes[displayStatus] || { label: displayStatus, color: '#007bff' };
            // 如果标签已存在，则累加数据
            var existingIndex = labels.indexOf(displayInfo.label);
            if (existingIndex >= 0) {
                data[existingIndex] += stats[status];
            } else {
                labels.push(displayInfo.label);
                data.push(stats[status]);
                backgroundColors.push(displayInfo.color);
            }
        });
        
        // 创建图表
        window.resultChart = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: labels,
                datasets: [{
                    data: data,
                    backgroundColor: backgroundColors,
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'right',
                    }
                }
            }
        });
    }
    
    // 更新趋势图表
    function updateTrendChart(stats) {
        var ctx = document.getElementById('trendChart').getContext('2d');
        
        // 如果图表已存在，先销毁
        if (window.trendChart && typeof window.trendChart.destroy === 'function') {
            window.trendChart.destroy();
        }
        
        // 准备数据
        // 按日期排序
        var dates = Object.keys(stats).sort();
        var passData = [];
        var failData = [];
        var errorData = [];
        var blockedData = [];
        
        dates.forEach(function(date) {
            passData.push(stats[date].PASS);
            failData.push(stats[date].FAIL);
            errorData.push(stats[date].ERROR);
            blockedData.push(stats[date].BLOCKED);
        });
        
        // 创建图表
        window.trendChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: dates,
                datasets: [
                    {
                        label: '通过',
                        data: passData,
                        borderColor: '#28a745',
                        backgroundColor: 'rgba(40, 167, 69, 0.1)',
                        fill: false,
                        tension: 0.1
                    },
                    {
                        label: '失败',
                        data: failData,
                        borderColor: '#dc3545',
                        backgroundColor: 'rgba(220, 53, 69, 0.1)',
                        fill: false,
                        tension: 0.1
                    },
                    {
                        label: '错误',
                        data: errorData,
                        borderColor: '#ffc107',
                        backgroundColor: 'rgba(255, 193, 7, 0.1)',
                        fill: false,
                        tension: 0.1
                    },
                    {
                        label: '阻塞',
                        data: blockedData,
                        borderColor: '#6c757d',
                        backgroundColor: 'rgba(108, 117, 125, 0.1)',
                        fill: false,
                        tension: 0.1
                    }
                ]
            },
            options: {
                responsive: true,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1
                        }
                    },
                    x: {
                        ticks: {
                            autoSkip: false,
                            maxRotation: 45,
                            minRotation: 45
                        }
                    }
                }
            }
        });
    }
    
    // 查看结果详情
    function viewResultDetail(id) {
        $.get('/api/testresults') // 这里应该获取单个结果的API，暂时用全部结果过滤
            .done(function(data) {
                var result = data.find(r => r.id == id);
                if (result) {
                    var statusClass = result.status === 'PASS' ? 'success' : result.status === 'FAIL' ? 'danger' : 'warning';
                    var statusText = result.status === 'PASS' ? '通过' : result.status === 'FAIL' ? '失败' : '错误';
                    
                    var detailHtml = `
                        <div class="modal" id="resultDetailModal" tabindex="-1">
                            <div class="modal-dialog modal-lg">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title">测试结果详情</h5>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                    </div>
                                    <div class="modal-body">
                                        <div class="card">
                                            <div class="card-body">
                                                <h5 class="card-title">${result.test_case ? result.test_case.name : '未知用例'}</h5>
                                                <p class="card-text">
                                                    <strong>状态:</strong> <span class="badge bg-${statusClass}">${statusText}</span><br>
                                                    <strong>执行时间:</strong> ${result.execution_time ? result.execution_time.toFixed(2) + ' 秒' : ''}<br>
                                                    <strong>执行时间:</strong> ${formatDate(result.executed_at)}<br>
                                                    ${result.log ? `<strong>日志:</strong><br><pre class="log-content bg-light p-2 border" style="white-space: pre-wrap; word-wrap: break-word; max-height: 300px; overflow-y: auto;">${escapeHtml(result.log)}</pre>` : ''}
                                                    ${result.screenshot_path ? `<strong>截图:</strong><br><img src="${result.screenshot_path}" class="img-fluid">` : ''}
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `;
                    
                    // 移除已存在的模态框
                    $('#resultDetailModal').remove();
                    
                    // 添加新模态框
                    $('body').append(detailHtml);
                    
                    // 显示模态框
                    $('#resultDetailModal').modal('show');
                }
            })
            .fail(function() {
                alert('加载结果详情失败');
            });
    }
    
    // 格式化日期
    function formatDate(dateString) {
        if (!dateString) return '';
        var date = new Date(dateString);
        return date.toLocaleString('zh-CN');
    }
    
    // 转义HTML特殊字符
    function escapeHtml(text) {
        var map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return text.replace(/[&<>"']/g, function(m) { return map[m]; });
    }
    
    // 切换标签页
    function switchTab(tabName) {
        // 更新激活状态
        activeTab = tabName;
        
        // 更新菜单项激活状态
        if (tabName === 'chart') {
            $('#chartTab').addClass('active');
            $('#logTab').removeClass('active');
            $('#chartContent').show();
            $('#logContent').hide();
        } else {
            $('#chartTab').removeClass('active');
            $('#logTab').addClass('active');
            $('#chartContent').hide();
            $('#logContent').show();
        }
        
        // 加载数据
        loadTestResults();
    }
    
    $(document).ready(function() {
        // 加载测试结果列表
        loadTestResults();
        
        // 刷新按钮点击事件
        $('#refreshResultsBtn').click(function() {
            loadTestResults();
        });
        
        // 标签页切换事件
        $('#chartTab').click(function() {
            switchTab('chart');
        });
        
        $('#logTab').click(function() {
            switchTab('log');
        });
        
        // 日期筛选变化事件
        $('#dateFilter').change(function() {
            dateFilter = $(this).val();
            loadTestResults();
        });
        
        // 清除日期筛选按钮点击事件
        $('#clearDateFilter').click(function() {
            $('#dateFilter').val('');
            dateFilter = '';
            loadTestResults();
        });
    });
</script>
{% endblock %}